package com.gougou.manager.web.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gougou.common.entity.EasyUIResult;
import com.gougou.common.entity.JsonBean;
import com.gougou.common.util.ControllerUtil;
import com.gougou.manager.pojo.TbContent;
import com.gougou.manager.service.MPTbContentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2018-09-07
 */
@RestController
@RequestMapping("/tbContent")
public class TbContentController {

    // 拿到当前类的日志对象
    private static final Logger LOGGER = LoggerFactory.getLogger(TbContentController.class);

    @Autowired
    private MPTbContentService tbContentService;

    // MQ所需
    @Autowired
    private RabbitTemplate rabbitTemplate;
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 分页查询内容管理信息
     * @param page 当前页
     * @param rows 页容量
     * @return
     */
    @RequestMapping("/content")
    public EasyUIResult getPageItem(@RequestParam Long categoryId, @RequestParam(defaultValue ="1" )int page, @RequestParam(defaultValue ="20" )int rows){
        try {
            EasyUIResult easyUIResult = new EasyUIResult();

            EntityWrapper<TbContent> contentWrapper = new EntityWrapper<TbContent>();
            contentWrapper.where("category_id = {0}",categoryId);
            contentWrapper.orderBy("created desc");//按照创建时间倒序
            //查询数据
            List<TbContent> itemlist = tbContentService.selectPage(new Page(page, rows),contentWrapper).getRecords();
            easyUIResult.setRows(itemlist);

            //查询总条数
            easyUIResult.setTotal((long) tbContentService.selectCount(contentWrapper));

            return easyUIResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加内容管理信息
     * @param content
     * @return
     */
    @RequestMapping( value = "/saveContent",method = RequestMethod.POST)
    public ResponseEntity<Void> saveContentVategory(TbContent content){

        try {
            Date date = new Date();
            content.setCreated(date);
            content.setUpdated(date);
            content.setId(null);
            tbContentService.insert(content);

            //发送消息到MQ的交换机，通知其他系统
            sendMsg("insert");

            return  ResponseEntity.status(HttpStatus.CREATED).body(null);

        }catch (Exception e){
            e.printStackTrace();
        }
        return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);

    }
    /**
     * 修改内容管理信息
     * @param content
     * @return
     */
    @RequestMapping( value = "/editContentVategory",method = RequestMethod.POST)
    public JsonBean updateContentVategory(TbContent content){
        Date date = new Date();
        try {
            content.setUpdated(date);
            tbContentService.updateAllColumnById(content);

            //发送消息到MQ的交换机，通知其他系统
            sendMsg("update");

            return ControllerUtil.setSuccessCode();

        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;

    }

    /**
     * 删除内容管理信息
     * @param ids
     * @return
     */
    @RequestMapping("/deleteContentVategory")
    public JsonBean deleteContentVategory(String ids){
        return deleteContentVategoryById(ids)?ControllerUtil.setSuccessCode():ControllerUtil.setFailCode("系统错误");
    }

    /**
     * 删除内容管理信息通过id
     * @param ids
     * @return
     */
    public boolean deleteContentVategoryById(String ids){

        // 直接替换
        String IdsSTR = ids.replaceAll(",", " or id=");


        EntityWrapper<TbContent> wrapper = new EntityWrapper<TbContent>();
        wrapper.where("id="+IdsSTR);


        tbContentService.delete(wrapper);

        //发送消息到MQ的交换机，通知其他系统
        sendMsg("delete");

        return true;
    }

    /**
     * 发送消息到MQ的交换机，通知其他系统
     * @param type
     */
    private void sendMsg(String type){
        try {
            Map<String, Object> msg = new HashMap<String, Object>();
            msg.put("type", type);
            msg.put("date", System.currentTimeMillis());
            this.rabbitTemplate.convertAndSend("content." + type, MAPPER.writeValueAsString(msg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

